package com.zy.web.demo.suanfa.consistencyHash;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author zy
 * @version 1.0
 * @date 2021/3/4 22:04
 */
public class Hash {

    public static void main(String[] args) {
        String[] tomcatServers = new String[]{"123.111.0.0","123.101.3.1","111.20.35.2","123.98.26.3"};
        SortedMap<Integer,String> map = new TreeMap<>();

        for (String tomcatServer : tomcatServers) {
            // Math.abs获取绝对值
            int abs = Math.abs(tomcatServer.hashCode());
            map.put(abs,tomcatServer);
        }


        String[] clients = new String[]{"10.78.12.3","113.25.63.1","126.12.3.8"};
        for (String client : clients) {

            int abs = Math.abs(client.hashCode());
            SortedMap<Integer, String> integerStringSortedMap = map.tailMap(abs);
            if (integerStringSortedMap.isEmpty() ){
                Integer integer = map.firstKey();
                System.out.println("客户端:"+client+"被:"+map.get(integer)+"代理");
            }else {
                Integer integer = integerStringSortedMap.firstKey();
                System.out.println("客户端:"+client+"被:"+integerStringSortedMap.get(integer)+"代理");
            }

        }

    }

}
